package handler

import (
	"context"
	"strconv"

	"github.com/360EntSecGroup-Skylar/excelize"

	"gitee.com/krio/grpc-go-server/dao/model/region"
	regionSvc "gitee.com/krio/grpc-go-server/internal/service/region"
)

type RegionCmdHandler struct {
	regionSvc *regionSvc.RegionService
}

func NewRegionCmdHandler(
	regionSvc *regionSvc.RegionService,
) *RegionCmdHandler {
	return &RegionCmdHandler{
		regionSvc: regionSvc,
	}
}

func (cr *RegionCmdHandler) AddFillData(file string) error {
	f, err := excelize.OpenFile(file)
	if err != nil {
		return err
	}

	// 获取 Sheet1 上所有单元格
	rows := f.GetRows("Sheet1")
	for _, row := range rows {
		if row[1] == "adcode" {
			continue
		}
		if row[1][1:len(row[1])] == "00000" { // 国
			adcode, _ := strconv.ParseInt(row[1], 10, 32)                 // nolint
			_, _ = cr.regionSvc.Add(context.Background(), &region.Region{ // nolint
				Name:     row[0],
				Adcode:   int32(adcode),
				CityCode: "",
				Pcode:    0,
				Level:    0,
			})
		} else if row[1][2:len(row[1])] == "0000" { // 省
			adcode, _ := strconv.ParseInt(row[1], 10, 32)                 // nolint
			_, _ = cr.regionSvc.Add(context.Background(), &region.Region{ // nolint
				Name:     row[0],
				Adcode:   int32(adcode),
				CityCode: row[2],
				Pcode:    100000,
				Level:    1,
			})
		} else if row[1][4:len(row[1])] == "00" { // 市
			adcode, _ := strconv.ParseInt(row[1], 10, 32)                 // nolint
			pcode, _ := strconv.ParseInt(row[1][0:3]+"000", 10, 32)       // nolint
			_, _ = cr.regionSvc.Add(context.Background(), &region.Region{ // nolint
				Name:     row[0],
				Adcode:   int32(adcode),
				CityCode: row[2],
				Pcode:    int32(pcode),
				Level:    2,
			})
		} else {
			adcode, _ := strconv.ParseInt(row[1], 10, 32)                 // nolint
			pcode, _ := strconv.ParseInt(row[1][0:4]+"00", 10, 32)        // nolint
			_, _ = cr.regionSvc.Add(context.Background(), &region.Region{ // nolint
				Name:     row[0],
				Adcode:   int32(adcode),
				CityCode: row[2],
				Pcode:    int32(pcode),
				Level:    3,
			})
		}
	}
	return nil
}
